## load necessary libraries
##
library(Cairo)

## initialize device
##
#Cairo(file="rademacher.png", type="png", width = 7, height = 7, pointsize = 12, record = getOption("graphics.recorecord"),
# rescale = c("R", "fit", "fixed"), xpinch, ypinch, bg = "transparent", canvas = "white",
# gamma = getOption("gamma"), xpos = NA, ypos = NA, buffered = getOption("windowsBuffered"),
# restoreConsole = TRUE)
CairoPNG(filename = "Complex%03d.png", width = 760, height = 350, pointsize = 12, bg = "white")
par(mfrow=c(1,2))

## Some global variables
##
sampling.frequency <- 1024 
sampling.delta <- 1/sampling.frequency 

## Function definition
##
sample.f1 <- 200 # Hz 
sample.f2 <- 78 # Hz
sample.t <- seq(0,2*pi,by=sampling.delta)
sample.v <- 0.8*sin(2*pi*sample.f1*sample.t) + 0.4*cos(2*pi*sample.f2*sample.t) + 31

## Plot function
##
plot(0,0,col="#00000000",ylim=c(29.8,32.2), xlim=c(0,0.05),xlab="X",ylab="Y",main="Complex function example")
lines(sample.t, sample.v, lwd=2, col=heat.colors(32)[15])

## FFT stuff goes in here
##
sample.fft <- fft(sample.v)
sample.f.Nyquist <- 1 / 2 / sampling.delta
sample.f <- sample.f.Nyquist * c(seq(length(sample.t)/2), -rev(seq(length(sample.t)/2))) / (length(sample.t)/2)
## plot it
plot(sample.f[2:length(sample.f)], Mod(sample.fft)[2:length(Mod(sample.fft))]/length(Mod(sample.fft)), xlim=c(-300,300), type='o', lwd=2, 
 col=heat.colors(32)[15], xlab="Frequency, Hertz", ylab="Power", main="Simple spectral analysis")

dev.off()
